package com.example.springbootvuetest.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springbootvuetest.Utils.TokenUtils;
import com.example.springbootvuetest.base.Result;
import com.example.springbootvuetest.entity.dto.UserDto;
import com.example.springbootvuetest.mapper.AdminMapper;
import com.example.springbootvuetest.mapper.UserMapper;
import com.example.springbootvuetest.entity.User;
import com.example.springbootvuetest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean updateUserStatusById(Integer id, Integer status) {
        boolean b = userMapper.updateUserStatus(id, status);
        return b;
    }

    @Override
    public boolean updatePassword(String newPassword, String oldPassword, String id) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        User user = userMapper.selectOne(queryWrapper);
        if (user.getUserPassword().equals(oldPassword)) {
            user.setUserPassword(newPassword);
            userMapper.updateById(user);
            return true;
        }
        return false;
    }

    @Override
    public Result<UserDto> login(String accountNumber, String userPassword) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.eq("user_password", userPassword).eq("account_number", accountNumber);
        User one = getOne(queryWrapper);
        if (null == one) {
            return Result.error();
        }
        String token = TokenUtils.getToken(String.valueOf(one.getId()), userPassword, "user");
        UserDto userDto = new UserDto();
        BeanUtil.copyProperties(one, userDto, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        userDto.setToken(token);
        return Result.success(userDto);
    }

    @Override
    public Result register(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.eq("user_password", user.getUserPassword()).eq("account_number", user.getAccountNumber());
        User one = getOne(queryWrapper);
        if (one != null) {
            return Result.error("此用户已经存在");
        }
        User user1 = new User();
        user1.setNickname(user.getNickname());
        user1.setUserPassword(user.getUserPassword());
        user1.setAccountNumber(user.getAccountNumber());
        user1.setAvatar("http://localhost:8080/image?imageName=file16469605582781002123.jpg");
        boolean flag = save(user1);
        return flag ? Result.success() : Result.error();
    }
}
